package com.uottawa.library.controller;

import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.uottawa.library.domain.User;
import com.uottawa.library.service.UserService;
 
/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(name="/LoginServlet",  urlPatterns={"/login.do"})

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private UserService userService = new UserService();
	
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        // get request parameters for userID and password
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        
        User user = userService.login(userName, password);
        
        if(user == null) {
        	request.setAttribute("error", "invalid login");
        	request.getRequestDispatcher("/index.jsp").forward(request, response);
        	return;
        }
        request.getSession().setAttribute("user", user);
        response.sendRedirect("home.jsp");
    }
 
}